package com.haoshuang.zhouzhoubang.ui.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log

import androidx.recyclerview.widget.LinearLayoutManager
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityExaminationBinding
import com.haoshuang.zhouzhoubang.model.bean.ExamQuestionBean
import com.haoshuang.zhouzhoubang.model.bean.ExamQuestionItem
import com.haoshuang.zhouzhoubang.model.bean.QuestionBean
import com.haoshuang.zhouzhoubang.ui.adapter.QuestionAdapter
import com.haoshuang.zhouzhoubang.ui.vm.ExaminationViewModel2
import com.jeremyliao.liveeventbus.LiveEventBus
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.SpannableStringUtils
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import java.util.*



/**
 *  开始考试界面
 */
class ExaminationActivity3 : BaseVMActivity<ExaminationViewModel2, ActivityExaminationBinding>() {
    val TAG = "ExaminationActivity"
    var type = 2
    lateinit var examQuestionList: ExamQuestionBean
    lateinit var examination: ExamQuestionBean.ExamQuestionItem
    var position1 = 0
    var answerSize = 0

    var rightNum = 0

    /**积分*/
    var integral = 0

    var timer = Timer()
    var timerTask: TimerTask? = null
    private var seconds = 0
    var ids = 0
    var ids2 = 0
    override fun initView(savedInstanceState: Bundle?) {
        ids = intent.getIntExtra("ids", -1) // 文章id
        ids2 = intent.getIntExtra("ids2", -1) // 文章id
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "考试"
            updateTitleNumber()

            tvNext.setOnClickListener {
                var type4=0
                for (b in list){
                    if (b.is_Check==1){
                        type4=1
                    }
                }

                if (type4==0){
                    toast("请选择答案！")
                    return@setOnClickListener
                }else{
                    var str=""
                    for (b in list){
                        if (b.is_Check==1){
                            str=str+b.title+","
                        }
                    }
                    checkAnswers(str.substring(0,str.length-1))
                if (position1== examQuestionList.list.size){
                    timerTask?.cancel()
                    timer.cancel()

                    val rate = rightNum * 100 / examQuestionList.list.size  // 正确率
                    if (rate >= question_reate) {
                        toast("恭喜您认证通过")
                        vm.getData("service_ids" to ids2,"little_ids" to ids)
                    }else{
                        LiveEventBus.get<Boolean>("BJg").post(true)
                       // ToastUtil.showTextToast("不及格")
                        finish()
                    }
                }else{
                        examination = examQuestionList.list.get(position1++)
                        setData(examination)
                        updateTitleNumber()
                    }

                }



            }
        }
        timerTask = object : TimerTask() {
            override fun run() {
                seconds++
            }
        }
        timer.schedule(timerTask, 1000, 1000)
    }


    /**答案检查*/
    private fun checkAnswers(answer: String) {
        Log.e("checkAnswers",answer)
        if (answer == examination.true_answer) {
            rightNum++
            integral += examination.integral.toFloat().toInt()
        }

    }


   lateinit var adapter: QuestionAdapter
    var list= arrayListOf<QuestionBean>()
    override fun initData() {
        vm.getExamQuestion("skill_id" to ids)


        adapter= QuestionAdapter(list)
        binding.rvList.layoutManager= LinearLayoutManager(this)
        binding.rvList.adapter=adapter
        adapter.setOnItemClick { _, position ,_->
            if (list[position].is_Check==0){
                if (examination.question_type==1||examination.question_type==3){
                    for (b in list){
                        b.is_Check=0
                    }
                }
                list[position].is_Check=1
            }else{
                list[position].is_Check=0
            }
            adapter.notifyDataSetChanged()

        }
    }
    var question_reate=80
    override fun startObserve() {
        /*获取考试试题API响应数据*/
        vm.getExamQuestionData.observeState(this) {
            onLoading { }
            onError { _, msg ->
                toast(msg)
            }
            onSuccess {
                if (it != null) {
                    answerSize = it.total
                    question_reate = it.question_reate.toInt()
                    updateTitleNumber()

                    examQuestionList = it
                    if (it.list.isNotEmpty()) {
                        examination = it.list.get(position1++)
                        updateTitleNumber()
                       setData(examination)
                       /* replaceFragment(
                            ExaminationChildFragment.newInstance(
                                examQuestionItem,
                                ::checkAnswers
                            )
                        )*/
                    }
                }
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { _, msg ->
                dismissLoading()
                  toast(msg)
            }
            onSuccess {
                dismissLoading()
                finish()
            }
        }
        /*提交答题结果API响应数据*/
        vm.submitResultData.observeState(this) {
            onLoading { }
            onError { _, msg ->
                toast(msg)
            }
            onSuccess {
                finish()
            }
        }
    }

    private fun setData(examination: ExamQuestionBean.ExamQuestionItem) {
        if (position1== examQuestionList.list.size){
            binding.tvNext.setText("交卷")

        }else{

            binding.tvNext.setText("下一题")
        }
        list.clear()
        if (examination.question_type==3){
            list.add(QuestionBean(1,"正确","A",0))
            list.add(QuestionBean(2,"错误","B",0))
        }else{
            list.add(QuestionBean(1,examination.answer1,"A",0))
            list.add(QuestionBean(2,examination.answer2,"B",0))
            list.add(QuestionBean(3,examination.answer3,"C",0))
            list.add(QuestionBean(4,examination.answer4,"D",0))
        }

        adapter.notifyDataSetChanged()
        val title = let {
            if (examination.question_type==2){
                SpannableStringUtils(it,"【多选】${examination.title}").first("【多选】").textColor(R.color.c_3b76c2)
            }else{
                SpannableStringUtils(it,"【单选】${examination.title}").first("【单选】").textColor(R.color.c_3b76c2)
            }

        }
        binding.tvTitle90.text = title
    }


    /**更新题号的UI*/
    private fun updateTitleNumber() {
        binding.tvNumberAnswers.text = SpannableStringUtils(mActivity, "${position1}/${answerSize}")
            .first("/${answerSize}").textColor(R.color.c_33)
    }

    // 跳转后的页面返回回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            1 -> {
                if (resultCode == 200) {
                    val isFinish = data?.getBooleanExtra("isFinish", false) as Boolean
                    if (isFinish) {
                        finish()
                    } else {
                        position1 = 0
                        vm.getExamQuestion()
                    }
                    Log.e(TAG, "onActivityResult: $isFinish")
                }
            }
        }
    }

}